package com.cims.action.customer;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.cims.action.BaseAction;
import com.cims.bo.order.OrderItemBO;
import com.cims.bo.order.OrderItemBOImpl;
import com.cims.common.vo.Customer;
import com.cims.common.vo.Item;
import com.cims.common.vo.OrderItem;
import com.cims.dao.hibernate.HibernateUtil;

public class PurchaseAction extends BaseAction{

	/** serialVersionUID */
	private static final long	serialVersionUID	= 1L;

	public int					itemCount;

	public String				userId;

	private OrderItemBO			bo					= new OrderItemBOImpl();

	public String purchase(){
		HttpServletRequest request = ServletActionContext.getRequest();
		try{
			// For each number of cart item
			for(int i = 1; i <= itemCount; i++){
				OrderItem item = new OrderItem();
				item.setCustomer(HibernateUtil.findByID(Customer.class, Integer.parseInt(userId)));
				String productStr = request.getParameter("item_options_" + i);
				int length = productStr.split(":").length;
				String id = productStr.split(":")[length - 1].trim();
				item.setItem(HibernateUtil.findByID(Item.class, Integer.parseInt(id)));
				item.setDateStart(new Date());
				item.setDateOrder(new Date());
				item.setPrice(Double.parseDouble(request.getParameter("item_price_" + i)));

				// Many quantity for a product
				int quantity = Integer.parseInt(request.getParameter("item_quantity_" + i));
				if(quantity > 1){
					for(int j = 0; j < quantity; j++){
						OrderItem clone = new OrderItem();
						clone.setCustomer(item.getCustomer());
						clone.setItem(item.getItem());
						clone.setDateStart(new Date());
						clone.setDateOrder(new Date());
						clone.setPrice(item.getPrice());
						clone.setQuantity(1);
						bo.addOrderItem(clone);
					}
				}else{
					item.setQuantity(1);
					bo.addOrderItem(item);
				}
			}
			return SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
			return ERROR;
		}
	}

	public int getItemCount(){
		return itemCount;
	}

	public void setItemCount(int itemCount){
		this.itemCount = itemCount;
	}

}
